# -*- coding:utf-8 -*-
"""
# @File : import_views.py
# @Author:chen
# @Date : 2023/9/30
# @Desc :
"""
from django.shortcuts import render, redirect
from plan import myform
from django.views import View
from plan import models
from django.http import QueryDict,HttpResponse,JsonResponse
from copy import deepcopy
from django.db.models import Q
from django.urls import reverse
from django.contrib import auth
from django.contrib.auth.decorators import login_required #函数的装饰器
from django.utils.decorators import method_decorator  #函数的装饰器变成方法的装饰器
from openpyxl import load_workbook


def import_sku(request):  #载入产能原表，读取数据
    if request.method == 'POST':
        file = request.FILES.get('name_file')
        wb = load_workbook(file)
        sheet1 = wb.active
        L =[]
        for row1 in sheet1:
            row_list1 = []
            for i in row1:
                row_list1.append(i.value)
            L.append(row_list1)
        print(L)
        to_sku_name = [ i[0] for i in L ]
        sql_sku_name = models.SKU.objects.filter(name__in=to_sku_name).values_list('name')
        sql_name = []
        for i in sql_sku_name:
            sql_name.append(i[0])
        next_sku_list = []
        over_sku_list = []
        for d in L[1:]:
            if d[0] in sql_name:
                over_sku_list.append(d)
            else:
                next_sku_list.append(d)
        objs = []
        for i in next_sku_list:
            obj = models.SKU(name=i[0],cust_id=i[1],is_launched=i[2])
            objs.append(obj)
        objs_success = models.SKU.objects.bulk_create(objs)
        sucess_sku = '、'.join(i[0] for i in next_sku_list)
        over_sku = '、'.join(i[0] for i in over_sku_list)
        return HttpResponse('导入成功的机种：%s,导入失败的机种%s,原因是机种名已存在！'% (sucess_sku,over_sku))


    return render(request,'templates/import_excel/import_sku.html')

# 机种工程线别数据导入
def import_gy(request):
    if request.method =='POST':
        file = request.FILES.get('name_file')
        wb = load_workbook(file)
        sheet1 = wb.active
        L = []
        for row1 in sheet1:
            row_list1 = []
            for i in row1:
                row_list1.append(i.value)
            L.append(row_list1)
        objs = []
        for i in L[1:]:
            sku_obj = models.SKU.objects.filter(name=i[0]).first()
            gy_obj = models.SkuProcessLineCpa(sku=sku_obj,process=i[1],line=i[2],sku_process=i[3])
            objs.append(gy_obj)
        print(objs)
        objs_success = models.SkuProcessLineCpa.objects.bulk_create(objs)
        return HttpResponse('工程面数据导入成功！')
    return render(request,'templates/import_excel/import_sku.html')


# 机种工程流程数据导入
def import_gyflow(request):
    if request.method =='POST':
        file = request.FILES.get('name_file')
        wb = load_workbook(file)
        sheet1 = wb.active
        L = []
        for row1 in sheet1:
            row_list1 = []
            for i in row1:
                row_list1.append(i.value)
            L.append(row_list1)
        print(L)
        objs = []
        for i in L[1:]:
            sku_obj = models.SKU.objects.filter(name=i[0]).first()
            gyflow_obj = models.ProcessFlow(sku=sku_obj, proToOne=i[1], proToTwo=i[2], proToThr=i[3],
                proToFou=i[4],proToFiv=i[5],proToSix=i[6],proToSen=i[7],proToEng=i[8],flow=i[9]
                                            )
            objs.append(gyflow_obj)
        objs_success = models.ProcessFlow.objects.bulk_create(objs)
        return HttpResponse('机种工程流程数据导入成功！')
    return render(request,'templates/import_excel/import_sku.html')
    # # wb = openpyxl.load_workbook('./cn/机种工程面线别产能2022-06-07.xlsx')
    # # sheet1 = wb['sheet1']  #获取sheet1对象
    # wb = load_workbook(r'F:\python_code\dj1.11\dj111\数据导入模版\无锡松下机种数据导入.xlsx')
    # sheet1 = wb.active
    # cn_dict = {}
    # L =[]
    # for row1 in sheet1:
    #     row_list1 = []
    #     for i in row1:
    #         row_list1.append(i.value)
    #     L.append(row_list1)
    # # for i in L[1:]:
    #     # cn_dict[i[0]] = i[1]
    # list_1 = []
    # # for i in L[1:]:
    # #     dict_1 = {}
    # #     dict_1[L[0][0]] = i[0]
    # #     dict_1[L[0][1]] = i[1]
    # #     dict_1[L[0][2]] = i[2]
    # #     list_1.append(dict_1)
    # # print(cn_dict)
    # wb.close()
    # print(L)
    # return L


def import_cap(request):
    if request.method =='POST':
        file = request.FILES.get('name_file')
        wb = load_workbook(file)
        sheet1 = wb.active
        L = []
        for row1 in sheet1:
            row_list1 = []
            for i in row1:
                row_list1.append(i.value)
            L.append(row_list1)
        # print(L)
        objs = []
        for i in L[1:]:
            splc_obj = models.SkuProcessLineCpa.objects.filter(sku_process=i[0]).first()
            new_obj = models.Capacity(
                splc = splc_obj,
                cap=i[1]
            )
            objs.append(new_obj)
        models.Capacity.objects.bulk_create(objs)
        return HttpResponse('导入成功！！')
    return HttpResponse('测试')


def import_process_num(request):
    if request.method =='POST':
        file = request.FILES.get('name_file')
        wb = load_workbook(file)
        sheet1 = wb.active
        L = []
        for row1 in sheet1:
            row_list1 = []
            for i in row1:
                row_list1.append(i.value)
            L.append(row_list1)
        print(L)
        objs = []
        for i in L[1:]:
            sku = models.SKU.objects.filter(name=i[0]).first()
            splc_obj = models.SkuProcessLineCpa.objects.filter(sku=sku,process=i[1])
            cap_obj = models.Capacity.objects.filter(splc__in=splc_obj).update(process_num=i[2])
            print(cap_obj,'更新成功')
            # new_obj = models.Capacity(
            #     splc = splc_obj,
            #     cap=i[1]
            # )
            # objs.append(new_obj)
        return HttpResponse('数据测试成功！')
    return HttpResponse('测试')


def update_cap(request):
    if request.method == 'POST':
        file = request.FILES.get('name_file')
        wb = load_workbook(file)
        sheet1 = wb.active
        L = []
        for row1 in sheet1:
            row_list1 = []
            for i in row1:
                row_list1.append(i.value)
            L.append(row_list1)
        print(L)
        for i in L[1:]:
            obj = models.SkuProcessLineCpa.objects.filter(id=i[0]).update(sku_process = i[3])
            print(obj)
        # objs = []
        return HttpResponse('数据更新成功！')

    return HttpResponse('测试')


def new_sku(request):
    if request.method =='POST':
        file = request.FILES.get('name_file')
        wb = load_workbook(file)
        sheet1 = wb.active
        L = []
        for row1 in sheet1:
            row_list1 = []
            for i in row1:
                row_list1.append(i.value)
            L.append(row_list1)
        # print(L)
        dict_data = []
        for a in L[1:]:
            dict1 = dict(zip(L[0], a))
            dict_data.append(dict1)
        print(dict_data)
        for b in dict_data:
            # SKU表的存储
            sku_name = b.get('机种名')
            sku_obj = models.SKU.objects.filter(name=sku_name).first()
            print(sku_obj)
            new_sku_id = ''
            if sku_obj == None:  #sku.name存在数据库，需要添加工作
                cust_small_name = b.get('客户')
                cust_obj = models.Customer.objects.filter(small_name=cust_small_name).first()
                new_sku = models.SKU.objects.create(
                    cust_id = cust_obj.id,
                    name = sku_name,
                )
                new_sku_id = new_sku.id
                print('新机种添加成功！')
            else:  #客户已存在，获取sku.id
                new_sku_id = sku_obj.id
                print('已存在的机种获取id！')
            print(new_sku_id)

            # ProcessFlow存入与更新
            proToOne = b.get('工程1')
            proToTwo = b.get('工程2')
            proToThr = b.get('工程3')
            proToFou = b.get('工程4')
            proToFiv = b.get('工程5')
            proToSix = b.get('工程6')
            proToSen = b.get('工程7')
            proToEng = b.get('工程8')
            sys_process_list = ['镭射', 'P8', 'P5', 'P4', 'FAB', 'DIP', 'FCT1', '组装', '注胶', '浸胶','涂胶','None' ]
            process_list = []
            if proToOne != None:

                process_list.append(proToOne.upper())
                if proToTwo != None:
                    process_list.append(proToTwo.upper())
                if proToThr != None:
                    process_list.append(proToThr.upper())
                if proToFou != None:
                    process_list.append(proToFou.upper())
                if proToFiv != None:
                    process_list.append(proToFiv.upper())
                if proToSix != None:
                    process_list.append(proToSix.upper())
                if proToSen != None:
                    process_list.append(proToSen.upper())
                if proToEng != None:
                    process_list.append(proToEng.upper())
            # 判断手写的工程是否出错
            for i in process_list:
                if i not in sys_process_list:
                    return HttpResponse('所选的工程不在系统工程内，请重新填写-->%s'%i)

            flow_pro = '_'.join(process_list)
            # 通过sku.id查询工程列表是否存在，如果已存在是更新，不存在是新增
            pro_obj = models.ProcessFlow.objects.filter(sku_id=new_sku_id).first()
            if pro_obj == None:  #不存在添加
                new_pro_obj = models.ProcessFlow.objects.create(
                    sku_id = new_sku_id,
                    proToOne = proToOne,
                    proToTwo = proToTwo,
                    proToThr = proToThr,
                    proToFou = proToFou,
                    proToFiv = proToFiv,
                    proToSix = proToSix,
                    proToSen = proToSen,
                    proToEng = proToEng,
                    flow = flow_pro,

                    )
                print('新机种工程列表添加成功--->',new_pro_obj.sku)
            else:   #存在，更新
                new_pro_obj = models.ProcessFlow.objects.filter(sku_id=new_sku_id).update(
                    proToOne=proToOne,
                    proToTwo=proToTwo,
                    proToThr=proToThr,
                    proToFou=proToFou,
                    proToFiv=proToFiv,
                    proToSix=proToSix,
                    proToSen=proToSen,
                    proToEng=proToEng,
                    flow=flow_pro,
                )
                print('机种工程列表更新成功--->',sku_name)

            # 机种名工程线别数据添加,产能数据添加  #取线别的key  存储的线别的value
            sys_line = ['LS_1L', 'LS_2L', 'LS_3L', 'SMT_1L', 'SMT_2L', 'SMT_3L', 'SMT_4L', 'SMT_5L', 'SMT_6L', 'SMT_7L','SMT_8L', 'SMT_9L','AI_1L', 'AI_2L', 'AI_3L', 'DIP_F', 'DIP_FAB', 'DIP_C', 'DIP_M', 'DIP_TJ', 'DIP_TS', 'DIP_JJ',
                        'DIP_ZJ', 'DIP_ZZ','None']
            smt_sheet_num = b.get('SMT拼板')
            dip_sheet_num = b.get('DIP拼板')
            p8_num = b.get('P8点数')
            p4_num = b.get('P4点数')
            p5_num = b.get('P5点数')
            # if not smt_sheet_num.isdigit():
            if not isinstance(smt_sheet_num,int):
                return HttpResponse('SMT拼板输入数据不是数字类型！')
            # if not dip_sheet_num.isdigit():
            if not isinstance(dip_sheet_num,int):
                return HttpResponse('DIP拼板输入数据不是数字类型！')
            # if not p8_num.isdigit():
            if not isinstance(p8_num,int):
                return HttpResponse('P8点数输入数据不是数字类型！')
            # if not p4_num.isdigit():
            if not isinstance(p4_num,int):
                return HttpResponse('P4点数输入数据不是数字类型！')
            # if not p5_num.isdigit():
            if not isinstance(p5_num,int):
                return HttpResponse('P5点数输入数据不是数字类型！')

            for i in range(1,9):
                process1 = b.get('工程%s'%i)
                new_line = b.get('工程%s_线别'%i)
                new_speed = b.get('工程%s_秒/台'%i)

                if process1 ==None:
                    break
                if not all([process1,new_line,new_speed]):
                    return HttpResponse('工程%s及线别和时间没有填写完整，请重新检查！'%i)
                if process1 not in sys_process_list:
                    return HttpResponse('工程%s填写的工程名不合法！机种：%s'%(i,sku_name))
                if new_line not in sys_line:
                    return HttpResponse('工程%s填写的工程线别不合法！机种：%s' %(i,sku_name))
                # if not new_speed.isdigit():
                if not isinstance(new_speed,int):
                    return HttpResponse('工程%s填写的工程%s_秒/台不合法！机种：%s' % (i,i, sku_name))
                line_value = line_dict.get(new_line)
                sku_process = sku_name + '_' + process1 + '_' + line_value

                process1 = process1.upper()
                print(new_sku_id,process1,new_line,sku_process)
                cap_obj = models.SkuProcessLineCpa.objects.filter(sku_id = new_sku_id,process = process1,line = new_line).first()
                print(cap_obj )
                print('*'*90)
                cap_id = ''
                if cap_obj ==None:
                    cap_obj = models.SkuProcessLineCpa.objects.create(
                        sku_id = new_sku_id,
                        process = process1,
                        line = new_line,
                        sku_process = sku_process
                    )
                    cap_id = cap_obj.id
                    print('创建cap成功')
                else:
                    cap_id = cap_obj.id
                    print('赋值cap成功')
                capacity_obj = models.Capacity.objects.filter(splc=cap_obj)
                print(capacity_obj)
                print('9'*90)
                if capacity_obj.first() == None:
                    if process1 == 'P8':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        process_num = p8_num
                        obj = models.Capacity.objects.create(
                            splc=cap_obj,
                            cap=int(sku_process_line_cap),
                            cycle_time=new_speed,
                            process_num = p8_num,
                            sheet_num = smt_sheet_num,
                        )

                        print('创建成功！sku:%s,工程面：%s，线别：%s'%(sku_name,process1,new_line))
                    elif process1 == 'P4':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        process_num = p4_num
                        obj = models.Capacity.objects.create(
                            splc=cap_obj,
                            cap=int(sku_process_line_cap),
                            cycle_time=new_speed,
                            process_num=p4_num,
                            sheet_num = smt_sheet_num,
                        )

                        print('创建成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
                    elif process1 == 'P5':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        process_num = p5_num
                        obj = models.Capacity.objects.create(
                            splc=cap_obj,
                            cap=int(sku_process_line_cap),
                            cycle_time=new_speed,
                            process_num=p5_num,
                            sheet_num=smt_sheet_num,
                        )
                        print('创建成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
                    elif process1 == '镭射':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        obj = models.Capacity.objects.create(
                            splc=cap_obj,
                            cap=int(sku_process_line_cap),
                            cycle_time=new_speed,
                            sheet_num=smt_sheet_num,
                        )
                        print('创建成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))

                    else:
                        sku_process_line_cap = 3600 / new_speed * 0.9 * smt_sheet_num * 10.5
                        sheet_num = dip_sheet_num
                        cycle_time = new_speed
                        obj = models.Capacity.objects.create(
                            splc=cap_obj,
                            cap=int(sku_process_line_cap),
                            cycle_time=new_speed,
                            sheet_num=dip_sheet_num,
                        )
                        print('创建成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
                else:
                    if process1 == 'P8':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        process_num = p8_num
                        capacity_obj.update(
                            cap=int(sku_process_line_cap),
                            sheet_num=smt_sheet_num,
                            cycle_time=new_speed,
                            process_num=p8_num,

                        )
                        print('更新成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
                    elif process1 == 'P4':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        process_num = p4_num
                        capacity_obj.update(
                            cap=int(sku_process_line_cap),
                            sheet_num=smt_sheet_num,
                            cycle_time=new_speed,
                            process_num=p4_num,

                        )
                        print('更新成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
                    elif process1 == 'P5':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        process_num = p5_num
                        capacity_obj.update(
                            cap=int(sku_process_line_cap),
                            sheet_num=smt_sheet_num,
                            cycle_time=new_speed,
                            process_num=p5_num,

                        )
                        print('更新成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
                    elif process1 == '镭射':
                        sku_process_line_cap = 3600 / new_speed * 0.97 * smt_sheet_num * 12
                        sheet_num = smt_sheet_num
                        cycle_time = new_speed
                        capacity_obj.update(
                            cap=int(sku_process_line_cap),
                            sheet_num=smt_sheet_num,
                            cycle_time=new_speed,

                        )
                        print('更新成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
                    else:
                        sku_process_line_cap = 3600 / new_speed * 0.9 * smt_sheet_num * 10.5
                        sheet_num = dip_sheet_num
                        cycle_time = new_speed
                        capacity_obj.update(
                            cap=int(sku_process_line_cap),
                            sheet_num=dip_sheet_num,
                            cycle_time=new_speed,

                        )
                        print('更新成功！sku:%s,工程面：%s，线别：%s' % (sku_name, process1, new_line))
        return HttpResponse('数据添加或更新成功！')

    return render(request,'templates/import_excel/new_sku.html')

#线别value
line_dict ={
    'LS_1L':'LS1L',
    'LS_2L':'LS2L',
    'LS_3L':'LS3L',
    'SMT_1L':'1L',
    'SMT_2L':'2L',
    'SMT_3L':'3L',
    'SMT_4L':'4L',
    'SMT_5L':'5L',
    'SMT_6L':'6L',
    'SMT_7L':'7L',
    'SMT_8L':'8L',
    'SMT_9L':'9L',
    'AI_1L':'AI1L',
    'AI_2L':'AI2L',
    'AI_3L':'AI3L',
    'DIP_F':'F线',
    'DIP_FAB':'FAB线',
    'DIP_C':'C线',
    'DIP_M':'M线',
    'DIP_TJ':'涂胶线',
    'DIP_TS':'测试线',
    'DIP_JJ':'浸胶线',
    'DIP_ZJ':'注胶线',
    'DIP_ZZ':'组装线',
}